package com.czl.module_service.viewmodel

import android.os.Bundle
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.RoomListBean
import com.czl.base.data.bean.tengyun.StorehouseBean
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.czl.base.util.SpHelper
import com.czl.module_service.R
import com.czl.module_service.bean.MenuItemModel
import com.czl.module_service.event.RoomListEvent
import com.czl.module_service.event.StockWarnBeanEvent
import com.czl.module_service.extension.AbsHandleSubscriber
import com.czl.module_service.system.Constants
import com.jeremyliao.liveeventbus.LiveEventBus

/**
 * @author by xubin,
 * @date on 2022/1/17.
 * PS: Not easy to write code, please indicate.
 */
class StoreManageViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var currentPage = 0

    val useNumStr = ObservableField("")

    val stockNumStr = ObservableField("")

    val warnNumStr = ObservableField("")

    val currentStore = ObservableField("")

    var storehouseBean: StorehouseBean? = null
    var list: List<StorehouseBean.StockWarnBean>? = null
    var roomList: List<RoomListBean>? = null
    val menu1: MutableList<MenuItemModel> by lazy {
        mutableListOf(
            MenuItemModel(
                R.mipmap.icn_idx_ruku,
                "入库",
                AppConstants.Router.Service.F_SERVICE_WAREHOUSING_HOME,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_lingyong,
                "领用",
                AppConstants.Router.Service.F_SERVICE_RECEIVE_HOME,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_jieyong,
                "借用",
                AppConstants.Router.Service.F_SERVICE_BORROW_HOME,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_guihuan,
                "归还",
                AppConstants.Router.Service.F_SERVICE_REMAND_HOME,
                false
            )
        )
    }

    val menu2: MutableList<MenuItemModel> by lazy {
        mutableListOf(
            MenuItemModel(
                R.mipmap.icn_idx_diaobo,
                "调拨",
                AppConstants.Router.Service.F_SERVICE_ALLOCATE_HOME,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_pan,
                "盘点",
                AppConstants.Router.Service.F_SERVICE_INVENTORY_HOME,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_chuzhi,
                "移位",
                AppConstants.Router.Service.F_SERVICE_SHIFT,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_wupinguanli,
                "物品管理",
                AppConstants.Router.Service.F_SERVICE_MANAGE_HOME,
                false
            ),
            MenuItemModel(
                R.mipmap.icn_idx_gongys,
                "供应商管理",
                AppConstants.Router.Service.F_SERVICE_SUPPLIER,
                false
            )
        )
    }

    val uc = UiChangeEvent()

    class UiChangeEvent {
        val loadStoreEvent: SingleLiveEvent<StorehouseBean?> = SingleLiveEvent()
        val loadCompleteEvent: SingleLiveEvent<StorehouseBean?> = SingleLiveEvent()
        val loadingEvent: SingleLiveEvent<Unit> = SingleLiveEvent()
        val switchStorehouse: SingleLiveEvent<StorehouseBean?> = SingleLiveEvent()
    }

    val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction {
        getAPPIndexTotal()
    })

    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 0
        getAPPIndexTotal()
    })

    val clickWarn: BindingCommand<Void> = BindingCommand(BindingAction {
        LiveEventBus.get(StockWarnBeanEvent::class.java).postOrderly(StockWarnBeanEvent(list))
        startActivity(AppConstants.Router.Service.F_SERVICE_STOCK_WARN)
    })

    val clickStock: BindingCommand<Void> = BindingCommand(BindingAction {
        LiveEventBus.get(RoomListEvent::class.java).postDelay(RoomListEvent(roomList), 200)
        startActivity(AppConstants.Router.Service.F_SERVICE_STOCK_LIST)
    })

    val clickSwitch: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.switchStorehouse.postValue(storehouseBean)
    })
    val clickSearch: BindingCommand<Void> = BindingCommand(BindingAction {
        startActivity(AppConstants.Router.Service.F_SERVICE_SEARCH_LIST)
    })

    override fun setToolbarRightClick() {
        super.setToolbarRightClick()
        val bundle = Bundle()
        bundle.putString("storehouseHome", "storehouseHome")
        startActivity(AppConstants.Router.Service.F_SERVICE_SCAN, bundle = bundle)
    }

    fun getStorehouseByUserId() {
        val userId = this.model.getLocalUserInfo()?.userId
        val userName = this.model.getLocalUserInfo()?.userName
        userId?.let { SpHelper.encode(Constants.SpKey.STOREHOUSE_USER_ID, it) }
        userName?.let { SpHelper.encode(Constants.SpKey.STOREHOUSE_USER_NAME, it) }
        model.mTengYunHttpDataSource
            .getStorehouseByUserId(
                GsonUtils.toJson(
                    mapOf(
                        "companyId" to model.getUserData()?.companyId,
                        "userId" to userId,
                        "roomInfo" to 1
                    )
                )
            )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe {
                uc.loadingEvent.postValue(null)
            }
            .subscribe(object :
                AbsHandleSubscriber<BaseBean<StorehouseBean>>(loadService = loadService) {
                override fun onSuccess(t: BaseBean<StorehouseBean>) {
                    if (t.state == 0) {
                        storehouseBean = t.data
                        t.data?.let {
                            uc.loadStoreEvent.postValue(it)
                        }
                    }
                }

                override fun onFailed(msg: String?) {
                    showErrorToast(msg)
                }
            })
    }

    fun getAPPIndexTotal() {
        model.mTengYunHttpDataSource
            .getAPPIndexTotal(
                GsonUtils.toJson(
                    mapOf(
                        "storehouseId" to SpHelper.decodeInt(Constants.SpKey.STOREHOUSE_ID)
                    )
                )
            )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<StorehouseBean>>() {
                override fun onResult(t: BaseBean<StorehouseBean>) {
                    if (t.state == 0) {
                        currentPage++
                        t.data?.useNum?.let {
                            useNumStr.set(it.toString())
                        }

                        t.data?.stockNum?.let {
                            stockNumStr.set(it.toString())
                        }
                        var count = 0
                        t.data?.stockWarnList?.forEach { i ->
                            i.stockNum?.let {
                                count += it
                            }
                        }
                        warnNumStr.set(count.toString())
                        list = t.data?.stockWarnList
                        uc.loadCompleteEvent.postValue(t.data)
                    } else {
                        uc.loadCompleteEvent.postValue(null)
                    }
                }

                override fun onFailed(msg: String?) {
                    showErrorToast(msg)
                    uc.loadCompleteEvent.postValue(null)
                }

            })
    }
}